package com.p2p.front.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.annotation.LoginNeedless.LoginType;
import com.p2p.base.exception.BizException;
import com.p2p.base.model.BaseUser;
import com.p2p.base.page.PageVo;
import com.p2p.base.service.LoanStatusService;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.BorrowerPhoto;
import com.p2p.front.dal.model.LoanComment;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.LoanPhoto;
import com.p2p.front.dal.model.LoanVariation;
import com.p2p.front.dal.model.Tender;
import com.p2p.front.enums.PhotoType;
import com.p2p.front.service.BorrowerPhotoService;
import com.p2p.front.service.LoanCommentService;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.LoanPhotoService;
import com.p2p.front.service.LoanVariationService;
import com.p2p.front.service.TenderService;
import com.p2p.front.service.TransferService;
import com.p2p.front.service.UserInfoService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.BorrowerAuthUtil;
import com.p2p.front.web.form.LoanPageVo;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.result.AccountQueryResult;
import com.p2p.user.enums.UserAuthName;
import com.p2p.user.enums.UserInfoName;
import com.p2p.user.facade.UserQueryFacade;
import com.p2p.user.result.UserQueryResult;
import com.p2p.user.vo.UserInfoFullVO;

/**
 * 投标信息相关的controller
 * 
 * @author <a href="mailto:liyang@yiqihao.com">李阳</a>
 * @version 1.0
 */
@Controller
@RequestMapping("/loan")
public class LoanController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(LoanController.class);

	@Resource
	private LoanInfoService loanInfoService;

	@Resource
	private LoanVariationService loanVariationService;

	@Resource
	private AccountQueryFacade accountQueryFacade;

	@Resource
	private UserService userService;

	@Resource
	private UserQueryFacade userQueryFacade;

	@Resource
	private TenderService tenderService;

	@Resource
	private LoanPhotoService loanPhotoService;
	@Resource
	private BorrowerPhotoService borrowerPhotoService;
	@Resource
	private LoanCommentService loanCommentService;

	@Resource
	private LoanStatusService constService;

	@Resource
	private TransferService transferService;

	@Resource
	private UserInfoService userInfoService;

	@RequestMapping("/list")
	@LoginNeedless(loginType = LoginType.NEED_CURRENT_USER)
	public String list(LoanPageVo form, Model model) {
		form.init();
		// 前台status要>=12
		form.setFront(1);
		PageVo page = loanInfoService.list(form);
		List<LoanInfo> list = (List<LoanInfo>) page.getList();
		List<Long> loanIds = new ArrayList<Long>();
		List<Long> loanIdsForPic= new ArrayList<Long>();
		for (LoanInfo loanInfo : list) {
			
			loanIds.add(loanInfo.getLid());
			if(loanInfo.getPlid()!=null&&loanInfo.getPlid()>0){
				loanIdsForPic.add(loanInfo.getPlid());
			}
			loanIdsForPic.add(loanInfo.getLid());
			
			
		}
		if (loanIds.size() > 0) {
			Map<Long, LoanVariation> loanVariationMap = loanVariationService
					.findLoanVariationByIds(loanIds);
			Map<Long, List<LoanPhoto>> loanPhotoMap = loanPhotoService.findByLidListAndType(loanIdsForPic,1);
					
			for (LoanInfo loanInfo : list) {
				loanInfo.setLoanVariation(loanVariationMap.get(loanInfo
						.getLid()));
				loanInfo.setLoanPhotoList(loanPhotoMap.get(loanInfo.getLid()));
				if (loanInfo.getPlid() > 0) {
					List<LoanPhoto> plidPhotos = loanPhotoMap.get(loanInfo.getPlid());
					if(plidPhotos!=null&&plidPhotos.size()>0){
						List<LoanPhoto> lidPhotos  = loanInfo.getLoanPhotoList();
						if(lidPhotos==null||lidPhotos.size()==0){
							loanInfo.setLoanPhotoList(plidPhotos);
						}else{
							lidPhotos.addAll(plidPhotos);
						}
					}
					
				}
			}

		}
		model.addAttribute("page", page);
		return "loan/list";
	}

	/**
	 * 为了菜单高亮，把债权转让的请求移动到投标下面
	 */
	@RequestMapping("/transferlist")
	@LoginNeedless
	public String transferlist(LoanPageVo form, ModelMap map) {
		form.init();
		form.getParams().put("ge_t.exptime", System.currentTimeMillis() + "");
		
		PageVo page = transferService.searchListPage(form);
		map.addAttribute("page", page);
		return "/transfer/list";
	}

	@RequestMapping("/{lid}")
	@LoginNeedless(loginType = LoginType.NEED_CURRENT_USER)
	public String loanDetail(Model model, @PathVariable("lid") long lid) {

		// 获取贷款信息
		LoanInfo loanInfo = loanInfoService.getLoanInfoById(lid);

		if (loanInfo == null) {
			throw new BizException(null, "参数错误，标不存在");
		}
		LoanVariation loanVariation = loanVariationService.getByLoanId(lid);
		Long uid = loanInfo.getUid();
		UserQueryResult userQueryResult = userQueryFacade
				.getUserInfoById(String.valueOf(uid));
		if (!userQueryResult.isSuccess()) {
			throw new BizException(null, "用户不存在,id=" + uid);
		}

		UserInfoFullVO userInfoFullVO = userQueryResult.getUserInfoFullVO();
		// 获取贷款人基本资料
		// User userInfo =
		// userService.findById(String.valueOf(loanInfo.getUid()));
		Map<Integer, Character> authMap = userInfoFullVO.getAuthMap();
		Map<String, Character> userAuthMap = new HashMap<String, Character>();
		for (UserAuthName authName : UserAuthName.values()) {
			userAuthMap.put(authName.name(), authMap.get(authName.getIndex()));
		}
		// 获取投标记录
		List<Tender> tenderList = tenderService.findSuccesedByLoanId(loanInfo.getLid());

		// 获取贷款人相关资料图片信息
		List<LoanPhoto> loanPhotoList = null;
		/*if (loanInfo.getPlid() > 0) {
			loanPhotoList = loanPhotoService.findByLidList(loanInfo.getLid(),
					loanInfo.getPlid());
		} else {
			loanPhotoList = loanPhotoService.findByLidAndType(loanInfo.getLid(),1);
		}*/
		loanPhotoList = loanPhotoService.findByLid(loanInfo.getLid());
		if (loanInfo.getPlid() > 0) {
			List<LoanPhoto> ploanPhotoList = loanPhotoService.findByLidAndType(loanInfo.getPlid(),1);
			loanPhotoList.addAll(ploanPhotoList);
		}
		
		
		List<BorrowerPhoto> borrowerPhotoList = borrowerPhotoService.findByUid(
				uid, PhotoType.BORROWER_INFO.getCode());
		// 获取留言信息
		List<LoanComment> loanCommentList = loanCommentService
				.findByLoanId(loanInfo.getLid());

		model.addAttribute("loanInfo", loanInfo);
		model.addAttribute("loanVariation", loanVariation);
		model.addAttribute("userInfoFullVO", userInfoFullVO);
		model.addAttribute("userAuthMap", userAuthMap);
		model.addAttribute("tenderList", tenderList);
		model.addAttribute("loanPhotoList", loanPhotoList);
		model.addAttribute("borrowerPhotoList", borrowerPhotoList);
		model.addAttribute("loanCommentList", loanCommentList);
		Map<String, Object> auth = userInfoService.getOne(String.valueOf(uid),
				UserInfoName.BORROWER_AUTH);
		String infoValue = MapUtils.getString(auth, "info_value");
		Map<String, Object> authParams = BorrowerAuthUtil
				.authToParams(infoValue);
		model.addAllAttributes(authParams);
		BaseUser user = getCurrentUser();
		if (user != null) {
			AccountQueryResult result = accountQueryFacade
					.getAccountByUserId(user.getId());
			if (result.isSuccess()) {
				model.addAttribute("accountVO", result.getAccountVO());
			}
		}

		return "loan/detail";
	}

}
